package com.ljyh.forum.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ljyh.forum.config.JwtUtil;
import com.ljyh.forum.dto.PostDTO;
import com.ljyh.forum.entity.Post;
import com.ljyh.forum.service.PostService;
import com.ljyh.forum.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 帖子控制器
 */
@RestController
@RequestMapping("/posts")
@Tag(name = "帖子接口", description = "帖子相关接口")
public class PostController {

    @Autowired
    private PostService postService;

    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping
    @Operation(summary = "获取帖子列表")
    public ApiResponse<Page<PostDTO>> getPosts(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(defaultValue = "new") String sort) {
        
        Page<PostDTO> posts = postService.getPostsPage(page, size, categoryId, sort);
        return ApiResponse.success("查询成功", posts);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取帖子详情")
    public ApiResponse<PostDTO> getPostDetail(@PathVariable Long id) {
        PostDTO post = postService.getPostDetail(id);
        if (post != null) {
            // 增加浏览量
            postService.increaseViewCount(id);
            return ApiResponse.success("查询成功", post);
        } else {
            return ApiResponse.error(404, "帖子不存在");
        }
    }

    @PostMapping
    @Operation(summary = "发布帖子")
    public ApiResponse<Void> publishPost(@Valid @RequestBody PostRequest request) {
        // 从JWT token中获取用户ID
        Long userId = SecurityUtils.getCurrentUserId(jwtUtil);
        
        if (userId == null) {
            return ApiResponse.error(401, "用户未认证");
        }
        
        boolean success = postService.publishPost(
            request.getTitle(), 
            request.getContent(), 
            request.getCategoryId(), 
            userId
        );
        
        if (success) {
            return ApiResponse.success("发布成功", null);
        } else {
            return ApiResponse.error(400, "发布失败");
        }
    }

    @GetMapping("/hot")
    @Operation(summary = "获取热门帖子")
    public ApiResponse getHotPosts(@RequestParam(defaultValue = "10") int limit) {
        return ApiResponse.success("查询成功", postService.getHotPosts(limit));
    }

    @GetMapping("/user/{userId}")
    @Operation(summary = "获取指定用户的帖子列表")
    public ApiResponse<Page<PostDTO>> getUserPosts(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Page<PostDTO> posts = postService.getUserPosts(userId, page, size);
        return ApiResponse.success("查询成功", posts);
    }

    @GetMapping("/featured")
    @Operation(summary = "获取精华帖子列表")
    public ApiResponse<Page<PostDTO>> getFeaturedPosts(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Page<PostDTO> posts = postService.getFeaturedPosts(page, size);
        return ApiResponse.success("查询成功", posts);
    }

    /**
     * 帖子请求体
     */
    public static class PostRequest {
        @NotBlank(message = "标题不能为空")
        private String title;
        
        @NotBlank(message = "内容不能为空")
        private String content;
        
        private Integer categoryId;

        // getters and setters
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        public Integer getCategoryId() { return categoryId; }
        public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; }
    }

    /**
     * 统一API响应格式
     */
    public static class ApiResponse<T> {
        private int code;
        private String msg;
        private T data;

        public ApiResponse(int code, String msg, T data) {
            this.code = code;
            this.msg = msg;
            this.data = data;
        }

        public static <T> ApiResponse<T> success(String msg, T data) {
            return new ApiResponse<>(200, msg, data);
        }

        public static <T> ApiResponse<T> error(int code, String msg) {
            return new ApiResponse<>(code, msg, null);
        }

        // getters
        public int getCode() { return code; }
        public String getMsg() { return msg; }
        public T getData() { return data; }
    }
}
